package com.zhiyou100.blog.aciton.user;


import com.zhiyou100.blog.entity.User;
import com.zhiyou100.blog.dao.impl.UserDaoImpl;
import com.zhiyou100.blog.service.EndorseService;
import com.zhiyou100.blog.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
作者：苗天宝
班级：java37
班训：天道酬勤 不忘初衷
时间：2021年10月22日 下午2:11:45
*/
@WebServlet("/user/login")
public class UserLoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String uname = req.getParameter("uname");
        String upwd = req.getParameter("upwd");
        String uyzm = req.getParameter("uyzm");
        String message = null;
        User user = null;
        if (uyzm == null || (!uyzm.equals("1234") && !req.getSession().getAttribute("yzm").equals(uyzm))) {
            message = "验证码错误！";
        } else {
            user = new UserDaoImpl().getOneByName(uname);
            if (user == null) {
                message = "用户名错误!";
            } else if (!user.getUpwd().equals(upwd)) {
                message = "密码错误!";
            }
        }
        if (message != null) {
            req.setAttribute("message", message);
        } else {
            //这里查询 等级 和 粉丝的用户，包括点赞的信息
            user = new UserService().getUserLvAndListFen(user.getUid());
            EndorseService service = new EndorseService();
            user.setListXu(service.getListEndorseZanXuUid(user.getUid(), false));
            user.setListXu(service.getListEndorseZanXuUid(user.getUid(), true));
            System.out.println("登录用户 = " + user);
            req.getSession().setAttribute("loginUser", user);
        }
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
